package com.admin.domain.media;

import com.foxinmy.weixin4j.util.NameValue;
import com.foxinmy.weixin4j.util.ObjectId;
import com.qiniu.storage.model.FileInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 七牛
 *
 * @className QiniuMediaStorage
 * @author jinyu
 * @date Apr 28, 2017
 * @since JDK 1.8
 * @see
 */
@Component("qnMediaStorage")
public class QiniuMediaStorage implements MediaStorage<List<FileInfo>> {
    @Autowired
    private QiniuUploader qiniuUploader;

    @Override
    public void init() {
        // do what?
    }

    @Override
    public NameValue store(MultipartFile file) {
        try {
            String mediaId = ObjectId.get().toHexString();
            return qiniuUploader.upload(file.getInputStream(), mediaId);
        } catch (IOException e) {
            throw new MediaException("Failed to store file " + file.getOriginalFilename(), e);
        }
    }

    @Override
    public List<FileInfo> loadAll() {
        return qiniuUploader.list();
    }

    @Override
    public InputStream load(String mediaId) {
        return qiniuUploader.open(mediaId);
    }

    @Override
    public void deleteAll() {
        // are you sure?
    }
}
